package com.ihakul.logger;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import androidx.annotation.NonNull;

/**
 * {@link CrashCatcher}启用后，若程序发生错误并导致崩溃，则将错误信息导到{@link RecordFilter}进一步
 * 处理。
 *
 * @author Aaron
 * @version 2.1
 * Create at 2019/7/17
 */
final class CrashCatcher implements Thread.UncaughtExceptionHandler {
    private final Context mContext;

    private final String  mPackageName;
    private PackageInfo   mPackageInfo;
    private Thread.UncaughtExceptionHandler defaultUncaughtHandler;

    /*package*/ RecordFilter mHandler;
    CrashCatcher(@NonNull Context context) {
        mContext = context;
        mPackageName=context.getPackageName();

    }

    void start() {
        Thread.UncaughtExceptionHandler h=Thread.getDefaultUncaughtExceptionHandler();
        if (h != this) {
            Thread.setDefaultUncaughtExceptionHandler(this);
            defaultUncaughtHandler=h;
        }else return;

        try {
            mPackageInfo = mContext.getPackageManager().getPackageInfo(mPackageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void exit(/*boolean reboot*/) {
        // Restart the program after the 2000 millisecond.
//        if(reboot){
//            Intent restart = new Intent(Events.TASK_RESTART);
//            Object service = context.getSystemService(Context.ALARM_SERVICE);
//            PendingIntent pi = PendingIntent.getBroadcast(context, -1, restart,
//                    PendingIntent.FLAG_CANCEL_CURRENT);
//            if (!PlatformUtil.below(android.os.Build.VERSION_CODES.KITKAT)) {
//                ((AlarmManager) service).setExact(AlarmManager.RTC_WAKEUP,
//                        (System.currentTimeMillis() + 2000), pi);
//            } else {
//                ((AlarmManager) service).set(AlarmManager.RTC_WAKEUP,
//                        (System.currentTimeMillis() + 2000), pi);
//            }
//        }

        // free logger
        new IotLogger().with(mContext).freed();

        // Force the exit process!
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if (this.mPackageInfo == null) {
            this.defaultUncaughtHandler.uncaughtException(t, e);
        } else if(mHandler!=null){
            mHandler.put(e);
            exit(/*true*/);
        }
    }

}
